#!/usr/bin/env Python3
# -*- encoding:utf-8 -*-

import grpc
import logging

from osplugin.grpcpb import lcmservice_pb2_grpc
from osplugin.settings import enable_ssl, listen_ip, port
from osplugin.settings import private_key_certificate_chain_pairs
from osplugin.settings import root_certificates
from osplugin.settings import require_client_auth
from concurrent import futures
from osplugin.service.os_applcm_servicer import OsAppLCMServicer

_ONE_DAY_IN_SECONDS = 60 * 60 * 24


def serve(listen_addr):
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    lcmservice_pb2_grpc.add_AppLCMServicer_to_server(OsAppLCMServicer(), server)
    if enable_ssl:
        cert_config = grpc.ssl_server_credentials(
            private_key_certificate_chain_pairs=private_key_certificate_chain_pairs,
            root_certificates=root_certificates,
            require_client_auth=require_client_auth
        )
        server.add_secure_port(listen_addr, cert_config)
    else:
        server.add_insecure_port(listen_addr)

    logging.info("Starting server on %s", listen_addr)
    server.start()
    server.wait_for_termination()


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
    serve(listen_addr=listen_ip + ':' + str(port))
